package kt.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import kt.smpp.SmppParameter;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class CommonUtil {
	private static Logger logger = LogManager.getLogger(CommonUtil.class);
	
	public static SmppParameter loadSMSCDataFromConfig() throws IOException {
		System.out.println("Begin load SMSC config data");
		logger.info("Begin load SMSC config data");
		logger.info("load config file " + "./conf/gateway.conf");
		BufferedReader in = new BufferedReader(new FileReader("./conf/gateway.conf"));
		SmppParameter smppParam = new SmppParameter();
		String line = in.readLine();
		for (; line != null; line = in.readLine()) {
			line = line.trim();
			if (!isValidConfigLine(line)) {
				continue;
			}
			int idx = line.indexOf("=");
			if (idx <= 0) {
				System.out .println("Invalid config line (Seperator '=' is NOT found) " + line);
				logger .error("Invalid config line (Seperator '=' is NOT found) " + line);
				continue;
			}
			String name = line.substring(0, idx).trim();
			String value = line.substring(idx + 1).trim();

			if ("smsc_ip_address".equalsIgnoreCase(name)) {
				smppParam.hostName = value;
			}
			if ("smsc_port".equalsIgnoreCase(name)) {
				smppParam.port = Integer.parseInt(value);
			}
			if ("smsc_system_id".equalsIgnoreCase(name)) {
				smppParam.systemID = value;
			}
			if ("smsc_password".equalsIgnoreCase(name)) {
				smppParam.password = value;
			}
			if ("mobile_operator".equalsIgnoreCase(name)) {
				smppParam.operator = value;
			}
			if ("source_addr_npi".equalsIgnoreCase(name)) {
				smppParam.sourceNPI = Integer.parseInt(value);
			}
			if ("source_addr_ton".equalsIgnoreCase(name)) {
				smppParam.sourceTON = Integer.parseInt(value);
			}
			if ("source_addr".equalsIgnoreCase(name)) {
				smppParam.sourceAddress = value;
			}
			if ("process_immediately".equalsIgnoreCase(name)) {
				smppParam.processImmediately = Boolean.parseBoolean(value);
			}			
		}
		logger.info("Params from config " + smppParam);
		return smppParam;	
	}

	private static boolean isValidConfigLine(String line) {
		if (("".equals(line)) || (line.startsWith("#"))) {
			return false;
		}
		return true;
	}
}